<template>
  <el-card class="form-container" shadow="never">
    <el-form
      :model="content"
      :rules="rules"
      ref="contentFrom"
      label-width="150px"
    >
      <el-form-item label="标题：" prop="title">
        <el-input v-model="content.title" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="图片：" prop="content">
        <single-upload
          v-model="content.content"
          tip="提示：请上传 690x278（Px）尺寸的图片，大小不超过500K。"
        ></single-upload>
      </el-form-item>
      <el-form-item label="渠道：" prop="channel">
        <el-checkbox-group v-model="content.channel">
          <el-checkbox
            v-for="item in channelList"
            :label="parseInt(item.commonCode)"
            :key="item.commonCode"
            >{{ item.commonDesc }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="位置：" prop="popId">
        <el-table
          :header-cell-style="headerStyle"
          ref="multipleTable"
          :data="popIdType"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="名称" align="center">
            <template slot-scope="scope">{{ scope.row.label }}</template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item
        label="生效时间："
        :rules="[
          { required: true, message: '请选择生效时间', trigger: 'change' },
        ]"
      >
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          align="right"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="dateRangeChange"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('contentFrom')"
          >提交</el-button
        >
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import SingleUpload from '@/components/Upload/singleUpload'
import moment from 'moment'
import {
  contentGetById,
  contentSave,
  contentUpdate,
  commonList
} from '@/api/content'

const defaultContent = {
  title: null,
  channel: [], // 不可改
  popId: null,
  content: null,
  stime: '',
  etime: '',
  classified: '10',
  type: '1'
}
export default {
  name: 'AddContent',
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      parentId: 0,
      dateRange: [],
      content: Object.assign({}, defaultContent),
      channelList: [],
      popIdOptions: { '1': '首页', '2': '社区', '3': '学院', '4': '学习', '5': '服务' },
      popIdType: [
        { label: '全部', value: '' },
        { label: '首页', value: '1' },
        { label: '社区', value: '2' },
        { label: '学院', value: '3' },
        { label: '学习', value: '4' },
        { label: '服务', value: '5' }
      ],
      headerStyle: {
        background: ' #f2f6fc',
        height: '20px',
        'line-height': '20px'
      },
      pickerOptions: {},
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        channel: [{ required: true, message: '请选择渠道', trigger: 'blur' }],
        content: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        popIdType: [
          { required: true, message: '请选择位置', trigger: 'blur' }
        ]
      },
      multipleSelection: []
    }
  },
  mounted () {
    this.getChannelType()
    if (this.isEdit) {
      contentGetById({ id: this.$route.query.id }).then((response) => {
        this.content = response.data
        this.content.channel = Object.assign(
          response.data.channel,
          defaultContent
        )
        this.dateRange = [this.content.stime, this.content.etime]
        this.content.popId.split(',').map((item) => {
          this.$refs.multipleTable.toggleRowSelection(this.popIdType[item])
        })

        if (this.content.channel.length === 1) {
          const num = parseInt(this.content.channel)
          this.content.channel = []
          this.content.channel.push(num)
          // console.log(this.content.channel);
        } else {
          this.content.channel = eval('(' + this.content.channel + ')')
        }
      })
    } else {
      this.content = Object.assign({}, defaultContent)
    }
  },
  methods: {
    getChannelType () {
      const params = {
        commonType: 'channel'
      }
      commonList(params).then((response) => {
        this.channelList = response.data
      })
    },
    onSubmit (formName) {
      this.content.popId = this.multipleSelection.map((item) => { return item.value }).join(',')
      console.log(this.multipleSelection)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.isEdit) {
              this.content.channel = eval('(' + this.content.channel + ')')
              const params = {
                id: this.$route.query.id,
                ...this.content
              }
              contentUpdate(params).then((res) => {
                this.$message({
                  message: res.message,
                  type: res.code === 200 ? 'success' : 'error',
                  duration: 1000
                })
                if (res.code === 200) this.$router.back()
              })
            } else {
              this.content.channel = eval('(' + this.content.channel + ')')
              const params = {
                ...this.content
              }
              contentSave(params).then((res) => {
                this.$message({
                  message: res.message,
                  type: res.code === 200 ? 'success' : 'error',
                  duration: 1000
                })
                if (res.code === 200) this.$router.back()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.content = Object.assign({}, defaultContent)
    },
    back () {
      this.$router.go(-1)
    },
    dateRangeChange (e) {
      this.content.stime = moment(e[0]).format()
      this.content.etime = moment(e[1]).format()
    }
  }
}
</script>

<style scoped>
.form-container {
  position: relative;
  z-index: 0;
  width: 800px;
}
table.el-table__header thead {
  background: #f2f6fc !important;
  height: 30px;
  line-height: 30px;
}
</style>
